# -*- coding: utf-8 -*-

"""
@Datetime: 2019/2/14
@Author: Zhang Yafei
"""
from flask import jsonify, request, g
from application import db
from common.libs.helper import getCurrentDate
from common.libs.member.MemberService import MemberService
from common.models.food.wx_share_history import WxShareHistory
from common.models.member.Member import Member
from common.models.member.OauthMemberBind import OauthMemberBind
from web.controllers.api import route_api


@route_api.route('/member/login', methods=['GET', 'POST'])
def login():
    """
    小程序会员登录模块
    :return:
    """
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = 201
        resp['msg'] = '需要code'

    openid = MemberService.getWechatOpenid(code)
    if openid is None:
        resp['code'] = 202
        resp['msg'] = '调用微信出错'
        return jsonify(resp)

    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else 0
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''
    """
        判断是否已经注册过, 注册了直接返回一些信息
    """
    bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bind_info:
        # 未注册过会员的用户
        model_memeber = Member()
        model_memeber.nickname = nickname
        model_memeber.sex = sex
        model_memeber.avatar = avatar
        model_memeber.salt = MemberService.geneSalt()
        model_memeber.updated_time = model_memeber.created_time = getCurrentDate()
        db.session.add(model_memeber)
        db.session.commit()

        model_bind = OauthMemberBind()
        model_bind.member_id = model_memeber.id
        model_bind.type = 1
        model_bind.openid = openid
        model_bind.extra = ''
        model_bind.updated_time = model_bind.created_time = getCurrentDate()
        db.session.add(model_bind)
        db.session.commit()

        bind_info = model_bind

    member_info = Member.query.filter_by(id=bind_info.member_id).first()
    token = '{}#{}'.format(MemberService.genAuthCode(member_info), member_info.id)
    resp['data'] = {'token': token}

    return jsonify(resp)


@route_api.route('/member/check-reg', methods=['GET', 'POST'])
def checkReg():
    """
    检测会员是否注册
    :return:
    """
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = 201
        resp['msg'] = '需要code'

    openid = MemberService.getWechatOpenid(code)
    if openid is None:
        resp['code'] = 202
        resp['msg'] = '调用微信出错'
        return jsonify(resp)

    bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bind_info:
        resp['code'] = 203
        resp['msg'] = '未绑定'
        return jsonify(resp)

    member_info = Member.query.filter_by(id=bind_info.member_id).first()
    if not member_info:
        resp['code'] = -1
        resp['msg'] = '未查询到绑定信息'
        return jsonify(resp)

    token = '{}#{}'.format(MemberService.genAuthCode(member_info), member_info.id)
    resp['data'] = {'token': token}

    return jsonify(resp)


@route_api.route('/member/share', methods=['GET', 'POST'])
def member_share():
    """
    分享功能：如今官方对开发者将此功能关闭
    :return:
    """
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    url = req['url'] if 'url' in req else ''
    member_info = g.member_info
    model_share = WxShareHistory()
    if member_info:
        member_share.member_id = member_info.id
    model_share.share_url = url
    model_share.created_time = getCurrentDate()
    db.session.add(model_share)
    db.session.commit()
    return jsonify(resp)


@route_api.route('/member/info')
def member_info():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    member_info = g.member_info
    resp['data']['info'] = {
        'nickname': member_info.nickname,
        'mobile': member_info.mobile,
        'avatar_url': member_info.avatar,
    }
    return jsonify(resp)
